<template>
  <div class="container">
    <el-dialog :visible.sync="dialogVisible" width="1100px" :before-close="closeDialog" top="246px">
      <div class="dialogContent">
        <div class="video-player-container">
          <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
            :options="playerOptions" @contextmenu.native.prevent></video-player>
        </div>
        <div class="playlist">
          <div :class="{'playlistItem':true,'playing':item.playUrl==videoSrc}" v-for="item,index in playlist"
            :key="index">
            <el-tooltip class="item" effect="light" :content="item.videoName" placement="top" :enterable="false">
              <div class="playlistItemTitleContainer" @click="handlePlayListItemClick(item)">
                <div class="playlistItemTitle">
                  {{item.videoName}}
                </div>
                <div v-if="item.playUrl==videoSrc" class="playingIcon"></div>
              </div>
            </el-tooltip>
            <div class="playlistIcons">
              <img v-if="item.collect" @click="reqUpdateCollect(item,0)" class="collectIcon"
                src="https://img3.job1001.com/data_center/images/caseTableItemLiked.svg" />
              <img v-else @click="reqUpdateCollect(item,1)" class="collectIcon"
                src="https://img3.job1001.com/data_center/images/caseTableItemLike.png" />
              <template>
                <img @click="handleDownloadClick(item)" class="downloadBtnIcon"
                  src="https://img3.job1001.com/data_center/images/caseDownload.svg" />
              </template>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { campusVideos, campusCollect } from "@/api/mine.js";
import { download } from "@/utils/fileSaver";
export default {
  name: "videoPlayerDialog",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    //只是传进来做初始化，videoSrc用来判断正在播放状态，真正播放的是配置项里的playerOptions[sources][0][src]
    mediaSrc: {
      type: String,
      default: "",
    },
    mediaName: {
      type: String,
      default: "",
    },
    playingVideoId: {
      type: Number,
      default: "",
    },
  },
  data() {
    return {
      playlist: [],
      videoSrc: "",
      playerOptions: {
        // playbackRates: [0.75, 1.0, 1.25, 1.5, 1.75, 2.0], //播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        // preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            // type: this.videoSrc.includes("m3u8")
            //   ? "application/x-mpegURL"
            //   : "video/mp4", // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            type: "video/mp4",
            src: this.videoSrc, // 视频url地址
            // src: require('@/assets/01.mp4') // 视频url地址
          },
        ],
        // poster: require("xxxxx"), // 你的封面地址 // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true, // 全屏按钮
        },
      },
      rate: 1.0,
    };
  },
  watch: {
    mediaSrc: {
      handler(newValue, oldValue) {
        if (!newValue) return;
        this.videoSrc = newValue;
        this.$set(
          this.playerOptions.sources[0],
          "type",
          newValue.includes("m3u8") ? "application/x-mpegURL" : "video/mp4"
        );
        this.$set(this.playerOptions.sources[0], "src", newValue);
      },
      immediate: true,
    },
  },
  created() {
    this.reqGetPlaylist();
  },
  methods: {
    reqGetPlaylist() {
      if (!this.$route.query.id) {
        this.playlist.unshift({
          videoName: this.mediaName,
          url: this.mediaSrc,
          collect: true,
          videoId: this.playingVideoId,
        });
        return;
      }
      const params = {
        positionId: this.$route.query.id,
      };
      campusVideos(params)
        .then((res) => {
          if (res.code == 200) {
            this.playlist = res.data;
            if (
              !res.data.find((item) => item.playUrl == this.mediaSrc) &&
              this.mediaName &&
              this.mediaSrc
            ) {
              this.playlist.unshift({
                videoName: this.mediaName,
                url: this.mediaSrc,
                collect: true,
              });
            }
          } else {
            console.log(res);
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {});
    },
    handlePlayListItemClick(item) {
      if (!item.playUrl) {
        this.$message.error("此视频暂不可播放");
        return;
      }
      if (item.playUrl == this.videoSrc) {
        this.$message.warning("此视频正在播放中");
        return;
      }
      this.videoSrc = item.playUrl;
      //要替换配置项里的播放链接
      this.$set(
        this.playerOptions.sources[0],
        "type",
        item.playUrl.includes("m3u8") ? "application/x-mpegURL" : "video/mp4"
      );
      this.$set(this.playerOptions.sources[0], "src", item.playUrl);
      //要延迟 不然不生效
      setTimeout(() => {
        this.$refs.videoPlayer.player.play();
      }, 1000);
    },
    handlePlay() {
      console.log(this.$refs.videoPlayer._options);
    },
    closeDialog() {
      this.$emit("update:dialogVisible", false);
    },
    reqUpdateCollect(item, action) {
      if (!item.videoId && !this.playingVideoId) {
        return;
      }
      const params = {
        dataId: item.videoId || this.playingVideoId,
        dataType: 1, //1视频 2毕业案例
        action, //1新增收藏  0取消收藏
      };
      let message;
      switch (action) {
        case 1:
          message = "收藏";
          break;
        case 0:
          message = "取消收藏";
          break;

        default:
          break;
      }
      campusCollect(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(message + "成功！");
            //刷新弹窗的
            this.$set(item, "collect", action);
            //如果有外面的就刷新外面的
            this.$emit("refreshOuterVideoList");
          } else {
            this.$message.error(message + "失败！");
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleDownloadClick(item) {
      const suffixList = [".pdf", ".doc", "docx", "xls", "xlsx", "mp4"];
      const suffix = suffixList.includes(item.playUrl.slice(-4))
        ? item.playUrl.slice(-4)
        : ".mp4";

      download(item.playUrl, item.videoName + suffix);
    },
  },
};
</script>

<style scoped lang="scss">
.dialogContent {
  display: flex;
  flex-wrap: nowrap;
  border-radius: 8px;
  .video-player-container {
    flex: 1;
    width: 770px;
    height: 453px;
    // border-radius: 8px 0 0 8px;
    // overflow: hidden;
  }
  .video-player {
    width: 100%;
    height: 453px;
  }
  .playlist {
    width: 293px;
    max-height: 455px;
    overflow-y: scroll;
    background: #202020;
    border-radius: 0 8px 8px 0;
    padding: 42px 14px 0;
    &::-webkit-scrollbar {
      width: 4px;
      // background-color: #f1f4f9;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: rgba(207, 216, 230, 1);
      border-radius: 2px;
    }
    .playlistItem {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 14px;
      color: #999999;
      line-height: 20px;
      text-align: left;
      font-style: normal;
      margin-bottom: 10px;
      cursor: pointer;
      &:hover {
        color: #e4e4e4;
      }
      &.playing {
        .playlistItemTitle {
          color: #e4e4e4;
        }
      }
      .playlistItemTitleContainer {
        display: flex;
        align-items: center;
        .playlistItemTitle {
          width: 142px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-inline-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          font-style: normal;
        }
        @keyframes videoPlayingFrames {
          0% {
            background-position: -10px -10px;
          }

          100% {
            background-position: -118px -10px; //第一个参数是网页里的最后一个数字 https://www.toptal.com/developers/css/sprite-generator
          }
        }
        .playingIcon {
          width: 16px;
          height: 16px;
          margin-left: 8px;
          background-image: url("//img3.job1001.com/data_center/images/videoPlayingFrames/sprites.png");
          /* 雪碧图路径 */
          background-position: -10px -10px;
          background-size: 180px auto; //图的长度
          background-repeat: no-repeat;
          animation: videoPlayingFrames 1.5s steps(3) forwards infinite;
          // margin-top: -10px;
        }
      }
      .playlistIcons {
        display: flex;
        align-items: center;
        img {
          width: 18px;
          height: 18px;
          margin-right: 8px;
        }
      }
    }
  }
}

::v-deep .el-dialog__header {
  background-color: transparent;
  border-bottom: none;
  border-radius: 8px 8px 0 0;
  padding: 0;
}
::v-deep .el-dialog__body {
  border: none;
  background-color: transparent;
  border-radius: 0 0 8px 8px;
  padding: 0;
}
::v-deep .el-dialog,
.el-pager li {
  background-color: transparent;
}
::v-deep .el-dialog__headerbtn {
  top: 10px;
  right: 10px;
  z-index: 999;
  transform: scale(1.1);
}
::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: white;
}
</style>
